package stockService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet(urlPatterns = {"/img"})
public class imgService extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public imgService() {
        super();
        // TODO Auto-generated constructor stub
    }

    static String img = "img/error.jpg";
    static String code = loadData.stocks[loadData.cur].code;

    public static void setImg(int stat) {
        if (stat == -1) {
            stat = loadData.img;
        } else {
            loadData.img = stat;
        }
        code = loadData.stocks[loadData.cur].code;
        if (loadData.stocks[loadData.cur].name.equals("Error Stock")) {
            img = "img/error.jpg";
        } else {
            if (stat == 0) {
                img = "http://image.sinajs.cn/newchart/min/n/" + code + ".gif";
            } else if (stat == 1) {
                img = "http://image.sinajs.cn/newchart/daily/n/" + code + ".gif";
            } else if (stat == 2) {
                img = "http://image.sinajs.cn/newchart/weekly/n/" + code + ".gif";
            } else if (stat == 3) {
                img = "http://image.sinajs.cn/newchart/monthly/n/" + code + ".gif";
            }
        }
    }

    public static String getImg(int stat) {
        setImg(stat);
        return img;
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        try {
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            String stat = request.getParameter("id");
            out = response.getWriter();
            out.println(getImg(Integer.parseInt(stat)));
        } catch (Exception e) {
            out.print("error: img");
            e.printStackTrace();
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}